package com.xxwu.springblogsystem.controller;

import com.xxwu.springblogsystem.Contants;
import com.xxwu.springblogsystem.model.Blog;
import com.xxwu.springblogsystem.model.Result;
import com.xxwu.springblogsystem.model.User;
import com.xxwu.springblogsystem.service.UserService;
import com.xxwu.springblogsystem.utils.JWTUtils;
import com.xxwu.springblogsystem.utils.SecretyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/userController")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    /**
     * 用户登陆
     * 检验数据是否存在
     * 检验用户名或密码是否正确
     */
    public Result login(String userName, String password) {
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码为空");
        }
        User user = userService.getUserByName(userName);
        log.info(user.toString());
        if(user == null){
            return Result.fail("用户名错误");
        }
//        if(!user.getPassword().equals(password)){
//            return Result.fail("密码错误");
//        }
        if(!SecretyUtils.verify(password, user.getPassword())){
            return Result.fail("密码错误");
        }
        //验证通过，获取token
        Map<String, Object> claim = new HashMap<>();
        claim.put("userId", user.getId());
        claim.put("userName", user.getUserName());
        String token = JWTUtils.genJwt(claim);
        log.info("获取token：" + token);
        return Result.success(token);
    }

    /**
     * 根据用户id获取用户信息
     */
    @RequestMapping("/getUserInfo")
    public User getUserById(HttpServletRequest request) {
        //获取token
        String token = request.getHeader(Contants.USER_TOKEN);
        //获取用户id
        Integer id = JWTUtils.getUserIDFromToken(token);
        //根据id获取用户信息
        if(id != null){
            User user = userService.getUserById(id);
            user.setPassword("");
            return user;
        }
        return null;
    }

    /**
     * 根据博客id获取作者信息
     */
    @RequestMapping("/getAuthorInfo")
    public Result getBlogById(Integer id) {
        if(id == null || id <= 0){
            return Result.fail("博客id不正确");
        }
        User user = userService.getUserByBlogId(id);
        user.setPassword("");
        return Result.success(user);
    }
}
